<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
  <script src="https://unpkg.com/axios/dist/axios.min.js"></script>
  <script>
    // 添加请求拦截器
    axios.interceptors.request.use(function (config) {
      // 在发送请求之前做些什么
      
      return config;
    }, function (error) {
      // 对请求错误做些什么
      return Promise.reject(error);
    });

    // 添加响应拦截器
    axios.interceptors.response.use(function (response) {
      // 对响应数据做点什么
      //存储token
      const { authorization } = response.headers
      if(authorization){
        localStorage.setItem("token",authorization)
      }
      return response;
    }, function (error) {
      // 对响应错误做点什么
      return Promise.reject(error);
    });
  </script>
</head>

<body>
  <h1>登录页面</h1>
  <div>
    <div>用户名: <input id="username" /></div>
    <div>密码: <input type="password" id="password" /></div>
    <div><button id="login">登录</button></div>
  </div>

  <script>

    var username = document.getElementById('username');
    var password = document.getElementById('password');
    var login = document.getElementById('login');

    login.onclick = () => {
      // fetch("/api/login",{
      //   method: "POST",
      //   headers: {
      //     "Content-Type": "application/json"
      //   },
      //   body: JSON.stringify({
      //     username: username.value,
      //     password: password.value,
      //   })
      // }).then(res=>res.json()).then(res=>{
      //   username.value = ""
      //   password.value=""
      //   if(res.ok === 1){
      //     alert("登录成功")
      //     location.href = "/"
      //   }else{
      //     alert("登录失败")
      //   }
      // })
      axios.post("/api/login", {
        username: username.value,
        password: password.value,
      }).then(res => {
        console.log(res)
        // username.value = ""
        // password.value=""
        if (res.data.ok === 1) {
          alert("登录成功")
          location.href = "/"
        } else {
          alert("登录失败")
        }
      })
    }
  </script>
</body>

</html>